<?php


///////////////////////
// GLOBAL PARAMETERS //
///////////////////////

$prevy=0;

$bDebug = FALSE;

if(isset ($_GET['debug'])){
    $bDebug = TRUE;
}

$bPage_Open = FALSE;


$intSpaceBetweenWorkAndHomeEmailX = 75; // 150
$intSpaceBetweenWorkAndMobNumX = 42; // 85
$intLineSepBetFmlySize = 10;//20
$intSmallLineSepSize = 10;//20
$intLineSepSize = 13; //26
$intMinLeftPositionX = 25; //50
$HomeAddrHeightY = 45+2; //90
$familyspaceratio = 7; // for calc how much space a family will take up

$intLeftDetailsIndentX = 20; //40
$intFirstNameIndentX = 115;//165//92
$intFirstDetailsX = $intFirstNameIndentX;//92; //168
$intIndvRoleIndentX = $intFirstNameIndentX+60 ;// 150; // 300
$intSpaceBetweenHofX = 50 ;// 35 Space between list of head of family

$intLeftEmailDetailsIndentX = $intFirstDetailsX + 75;  // + 150
$intHomeTelephoneIndentX = 335; //360
$intLeftDetailsX = 60; //80
$intMinSepAfterAddrY = 1;    // spacing between families
$intPageCountPosY = 15; //8
$intPostalAddressSizeY = 45; //was 30

///////////////////////
//   font            //
///////////////////////
$NormalFont = "Helvetica";
$BoldFont = "Helvetica-Bold";


//TODO FONTS
//  $NormalFont = "Comic Sans MS";
//	$BoldFont = "Comic Sans MS Bold";

$tinyFontSize = 7; // orig 14     // Role
$smallFontSize = 8; // orig 16  // address
$smallmediumFontSize = 9; // orig 20 // first Name
$mediumFontSize = 10; // orig 20 // first Name
$mediumlargeFontSize = 11; // orig Surname 
$largeFontSize = 12; // orig 24  // Home PhoneNumber

$hugeFontSize = 20; // orig 40

///////////////////////
//   PAGE SIZE (A4)  //
///////////////////////
$intPageSizeX = 842;  // ISO Standard A4 width landscape
$intPageSizeY = 595;  // ISO Standard A4 length landscape
$intTopOfPageY = 570; // maximum top of page to use
$intTopOfPageX = 15;  // minimum left of page to use // where FAMIYL NAME Will appear
$intMinBottomPageY = 12;  // minimum bottom of page to use  42// was 12 without page footer
$intMinBottomPageY_withFooter = 44; //was 45

$intPage1LeftX = $intTopOfPageX;
$intPage1RightX = ($intPageSizeX/2)-($intTopOfPageX); 

$intPage1MidX = (($intPage1RightX - $intPage1LeftX)/2) + $intPage1LeftX;
$intPage2LeftX = ($intPageSizeX/2)+($intTopOfPageX);
$intPage2RightX = $intPageSizeX-$intTopOfPageX;
$intPage2MidX = (($intPage2RightX - $intPage2LeftX)/2) + $intPage2LeftX;
$intPageSize = 2; //values can be 1 or 2 (i.e. which half of A5 page)


$intImageWidth = 63;
/*
echo "intPage1LeftX  = $intPage1LeftX <p>";
echo "intPage1RightX = $intPage1RightX<p>";
echo "intPage1MidX = $intPage1MidX<p><p>";

echo "intPage2LeftX  = $intPage2LeftX <p>";
echo "intPage2RightX = $intPage2RightX<p>";
echo "<b>intPage2MidX = $intPage2MidX</b><p><p>";
echo "intPageSizeX = $intPageSizeX<p>";

exit;
*/
///////////////////////
// LINE CONSTRAINTS  //
///////////////////////
$intLineSpaceToLeaveAtBothEnds = 15; //40
$intLineSepLeftX = $intLineSpaceToLeaveAtBothEnds;
$intLineSepRightX = $intPageSizeX - $intLineSpaceToLeaveAtBothEnds-10; // 595 is A4 page width

/*
for every FamilyId,
add a mpge entry with the page number
end for

Get total page count

Work out page order (from algorithm)

for each L and R page, work out which family goes on which page and print for those FamilyIds.

create pdf in booklet form.
*/


///////////////////////////
// DEFAULT ITEMS TO SHOW //
///////////////////////////
$bShowPrivateResidentialAddressesAsXXX = TRUE;  // done
$bShowPrivateTelephoneNumbersAsXXX = TRUE;      // done
$bShowPrivateEmailAddressesAsXXX = TRUE;		//done
$bShowFamilyPicture = FALSE;
$bShowRole = FALSE;
$bShowGender = FALSE;
$bShowWorkPhoneNumber = FALSE;
$bShowWorkEmailAddress = FALSE;
$bShowHomeEmailAddress = FALSE;
$bShowMobilePhoneNumber = FALSE;
$bShowSchoolGrade = TRUE;
$bShowTitlePage = FALSE;
$bShowPageNumber = FALSE;
$bHidePrivateData = TRUE;
$bShowPageFooter = TRUE;
$bShowYA = FALSE;

//////////////////////////////////////////////////////
// GPAC Database is Copyright 2003 Colin Todd       //
// Written by Colin Todd - All rights reserved.     //
//                                                  //
// colintodd@myfastmail.com                         //
//////////////////////////////////////////////////////

//$start_time = $PACTS_cfg->utime() utime();

$bShowPrivateResidentialAddressesAsXXX = @$_GET['ShowPrivateRA'];
$bShowPrivateTelephoneNumbersAsXXX = @$_GET['ShowPrivatePN'];
$bShowPrivateEmailAddressesAsXXX = @$_GET['ShowPrivateEA'];
$bShowFamilyPicture = @$_GET['ShowFmlyPic'];
$bShowRole = @$_GET['ShowRole'];
$bShowGender = @$_GET['ShowGender'];
$bShowWorkPhoneNumber = @$_GET['ShowWrkPN'];
$bShowWorkEmailAddress = @$_GET['ShowWrkEA'];
$bShowHomeEmailAddress = @$_GET['ShowHomeEA'];
$bShowMobilePhoneNumber = @$_GET['ShowMob'];
//   $bShowSchoolGrade = @$_GET['ShowSchoolGde'];
//	$bShowTitlePage = @$_GET['ShowTitlePage'];
$bShowPageNumber = @$_GET['ShowPageNum'];
$bShowPageFooter = @$_GET['ShowPageFooter'];
$bShowYA = @$_GET['ShowYA'];
$intPageCount = @$_GET['StartPageNum']-1; // set count to 0
$bHidePrivateData = @$_GET['HidePrivateData'];


if ($bShowPageFooter == 'TRUE'){
    //Change page size if footer is not present
    $intMinBottomPageY = $intMinBottomPageY_withFooter;
} else {
    $intMinBottomPageY = $intMinBottomPageY ;
}




//$pageFamilyId[$pagenum][$FamilyId] = "x";

/*
    echo "<pre>";
    print_r(@$_GET);
    echo "</pre>";
*/

// decode input SQL from URL

$Indv_sql = html_entity_decode(@$_GET['indv_sql']);
$Indv_sql = urldecode($Indv_sql);

$Fmly_sql = html_entity_decode(@$_GET['fmly_sql']);
$Fmly_sql  = urldecode($Fmly_sql);

if(strlen(trim($Fmly_sql))==0) {
    $Fmly_sql = "TRUE";
}
if(strlen(trim($Indv_sql))==0) {
    $Indv_sql = "TRUE";
}

//$Indv_sql = " IndividualId > 119 AND IndividualId < 126  ";
//$Indv_sql = " IndividualId > 119 AND IndividualId < 127  ";
//$Indv_sql = " IndividualId = 84  ";
//$Indv_sql = " IndividualId = 120  ";
//$Fmly_sql = " Family.FamilyId > 50 AND Family.FamilyId < 100  ";
//$Fmly_sql = " Family.FamilyId > 50 AND Family.FamilyId < 75  ";

if(strpos($Indv_sql, "ChurchDirectoryIndicator")>0 ) {
} else {
    //		$Indv_sql .= " AND ChurchDirectoryIndicator = 'Y' ";
}


// workout how many families are to be part of the report
$sql_Fmly = "SELECT ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyPhoto, ".$PACTS_cfg->familytablename.".FamilyShortName FROM (Individual INNER JOIN Family ON ".$PACTS_cfg->individualtablename.".FamilyId = ".$PACTS_cfg->familytablename.".FamilyId) WHERE $Indv_sql AND $Fmly_sql GROUP BY ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyShortName ORDER BY ".$PACTS_cfg->familytablename.".FamilyShortName ASC";

// get count of the individuals in these families
//$sql_Fmly = "SELECT ".$PACTS_cfg->individualtablename.".IndividualId, ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyPhoto, ".$PACTS_cfg->familytablename.".FamilyShortName FROM (Individual INNER JOIN Family ON ".$PACTS_cfg->individualtablename.".FamilyId = ".$PACTS_cfg->familytablename.".FamilyId) WHERE $Indv_sql AND $Fmly_sql ORDER BY ".$PACTS_cfg->familytablename.".FamilyShortName ASC";

$result_Fmly = $PACTS_cfg->LogQuery($sql_Fmly,__LINE__,__FILE__);
$resultsnumber_Fmly = 0;
$resultsnumber_Fmly = @mysql_num_rows($result_Fmly);


if ($bDebug){
    echo "Get parameters :- <pre>";
    print_r($_GET);
    echo "</pre><br>";


    print "Number of familes to be in report = $resultsnumber_Fmly<br />";
}

//GEt ind per family count
//			$sql_Indvcnt = "SELECT COUNT(*) as Fmly_Indvcnt FROM Individual WHERE FamilyId = $FamilyId AND $Indv_sql ;";
$sql_Indvcnt = "SELECT FamilyId , COUNT(*) as Fmly_Indvcnt FROM Individual WHERE $Indv_sql   group by FamilyId ;";
$result_Fmly_Indvcnt = $PACTS_cfg->LogQuery($sql_Indvcnt,__LINE__,__FILE__ );
//			$row_Fmly_Indvcnt_a = mysql_fetch_array($result_Fmly_Indvcnt);

//			print "<pre>";
//			print_r($row_Fmly_Indvcnt);
//			print "</pre><hr><pre>";
while ($row = mysql_fetch_array($result_Fmly_Indvcnt,MYSQL_NUM)) {
    $row_Fmly_Indvcnt [$row[0]] = $row[1];
    if ($bDebug){
        print "Indv count in familes to be in report : ";
        print $row[0].",".$row[1]."<br />";
    }

    //					print $row[0].",".$row[1]."<br />";
}

//$row_Fmly_Indvcnt = $result_Fmly_Indvcnt ;
//			print "<pre>";
//			print_r($row_Fmly_Indvcnt);
//			exit;

if ($resultsnumber_Fmly ==0)  {
    print "The query returned NO families for the directory ($resultsnumber_Fmly )<br />";
    print "sql_Fmly is <p>";
    print "</pre>$sql_Fmly</pre>";
    exit;
} else {
    //	print "resultsnumber_Fmly= ($resultsnumber_Fmly )<br />";

    // Create New PDF document
    $pdf = pdf_new();
}


// initialise variables for start
$y = $intMinBottomPageY-1 ; // set over limit so that new page (page1) will be inserted
$prevy=$y;

$x = $intTopOfPageX;

$famcount=0;

if($resultsnumber_Fmly >0) {
    while ($row_Fmly = mysql_fetch_array($result_Fmly)) {
        $y = $y - 5; // a small separator
        //
        // Grab Family details
        //
        $HeadOfFamilyCount = 0;

        $FamilyId = $row_Fmly["FamilyId"];

        if ($bDebug){
            print "Reading FamilyId = $FamilyId<br />";
        }
        $sql_SingleFmly = "SELECT * FROM Family WHERE FamilyId= $FamilyId;";
        $result_SingleFmly = $PACTS_cfg->LogQuery($sql_SingleFmly,__LINE__,__FILE__);
        $row_SingleFmly = mysql_fetch_array($result_SingleFmly);


        $famcount+=1;
        $array[$FamilyId] = $row_SingleFmly ;

        // count the number of members in family
        $sql_Indvcnt = "SELECT FamilyId , COUNT(*) as Fmly_Indvcnt FROM Individual WHERE $Indv_sql   group by FamilyId ;";
        $Fmly_Indvcnt = $row_Fmly_Indvcnt[$FamilyId];

        if ($bDebug){
            print "Indv Count in FamilyId = $Fmly_Indvcnt <br />";
        }

        // Check if there individuals in the family
        if($Fmly_Indvcnt>0) {
            $Indv_FamilyShortName = $row_Fmly["FamilyShortName"]." ";
            // format family details

            if ($bDebug){
                print "Indv_FamilyShortName = $Indv_FamilyShortName <br />";
            }


            if($row_SingleFmly["ResidentialAddressPrivateIndicator"]=="Y" and $bHidePrivateData) {
                $Fmly_ResAddress = "";
            } else {
                $Fmly_ResAddress  = $PACTS_cfg->getFormattedResidentialAddress($FamilyId, chr(10),TRUE,FALSE,FALSE,FALSE ,FALSE , "", $bShowPrivateResidentialAddressesAsXXX, FALSE);
            }

            if($row_SingleFmly["MailingAddressIndicator"]=="N" and strlen($row_SingleFmly["PostalAddressLine1"])>0 ) {
                $Fmly_PostalAddress = $PACTS_cfg->getFormattedPostalAddress($FamilyId, chr(10),TRUE,FALSE,FALSE,FALSE , " ");
            } else {
                $Fmly_PostalAddress = "";
            }

            if (strlen(trim($Fmly_ResAddress))==0 and strlen(trim($Fmly_PostalAddress))>0){
                $Fmly_ResAddress = $Fmly_PostalAddress ;
                $Fmly_PostalAddress = "";
            }

            $Fmly_HomePhone = "xx";
            $Fmly_Photo = $row_Fmly["FamilyPhoto"];

            ////////////////////////////
            // Grab photo from database
            //
            /////////////////// Create tmp file //////////////////////////
            $bImage = FALSE;
            $pdf_im_width = 0;
            $pdf_im_height = 0;
            $pdf_im_ratio = 0;

            if (strlen($Fmly_Photo) > 0 and $bShowFamilyPicture){
                $tt = explode( " ", microtime());
                //	echo("random : ".(int)($tt[0] * time())."<p>");

                $filename = "".(int)($tt[0] * time()).".jpg";
                $handle = fopen($filename, 'wb');
                if (!$handle) {
                    print "Cannot open file ($filename)";
                    exit;
                }
                // Write $somecontent to our opened file.
                $bImage = FALSE;
                $pdf_im_width = 0;
                $pdf_im_height = 0;
                $pdf_im_ratio = 0;
                if(!is_null($Fmly_Photo) and strlen($Fmly_Photo)>0 ) {
                    if (!fwrite($handle, $Fmly_Photo)) {
                        print "Cannot write to file ($filename)";
                        exit;
                    }
                    else
                    {
                        $bImage = TRUE;
                        //								print "image filename  = ".$filename."<p>";
                        //$pim = pdf_open_image_file($pdf, "jpeg", $filename);
                        //$pdf_im_width = pdf_get_value($pdf, "imagewidth", $pim);
                        //$pdf_im_height = pdf_get_value($pdf, "imageheight", $pim);
                        $image_size =  getimagesize ($filename);
                        $pdf_im_width = $image_size[0];
                        $pdf_im_height = $image_size[1];

                        if ($bDebug){
                            print "image width = $pdf_im_width, height = $pdf_im_height<br />";
                        }

                        // $intImageWidth
                        $pdf_im_ratio = (double)$intImageWidth/$pdf_im_width;
                    }
                }
                else
                {
                    $bottom_image_Y = 100000;
                }
            } else
            {
                $bImage = FALSE;
            }
            ////////////////////////////
            // END Grab photo from database
            //
            ////////////////////////////

            if ($Fmly_Indvcnt==1){
                $maxFamilySize_Text = 74; // was 50
            } else {
                $maxFamilySize_Text = $intSmallLineSepSize*($Fmly_Indvcnt)*4+20; // was 50
            }

            if ($Fmly_Indvcnt==1) $maxFamilySize_Text = 74;
            if ($Fmly_Indvcnt==2) $maxFamilySize_Text = 74 + (1*$familyspaceratio);
            if ($Fmly_Indvcnt==3) $maxFamilySize_Text  = 74 + (1*$familyspaceratio);
            if ($Fmly_Indvcnt==4) $maxFamilySize_Text  = 74 + (2*$familyspaceratio);
            if ($Fmly_Indvcnt==5) $maxFamilySize_Text = 74 + (3*$familyspaceratio);
            if ($Fmly_Indvcnt==6) $maxFamilySize_Text  = 74 + (5*$familyspaceratio);
            if ($Fmly_Indvcnt>6) $maxFamilySize_Text  = 74 + (($Fmly_Indvcnt+1)*$familyspaceratio);

            if ($bDebug){
                print "** maxFamilySize_Text = $maxFamilySize_Text<br />";
                print "pdf_im_height = $pdf_im_height<br />";
            }


            $maxFamilySize_Text = $maxFamilySize_Text + $pdf_im_height;
            $PACTS_cfg->LogData("Fmly_Indvcnt = $Fmly_Indvcnt, maxFamilySize_Text = $maxFamilySize_Text, Family =".$row_Fmly["FamilyShortName"]);


            if ($maxFamilySize_Text < $HomeAddrHeightY){
                $maxFamilySize_Text = $HomeAddrHeightY ;
            }

            if (strlen($Fmly_PostalAddress)>0) {
                $maxFamilySize_Text = $maxFamilySize_Text + $intPostalAddressSizeY;
            }

            $maxFamilySize_Pic = $pdf_im_height; // was 50

            if ($bDebug){
                print "maxFamilySize_Text = $maxFamilySize_Text<br />";
            }

            //				$maxFamilySize = max($maxFamilySize_Text, $maxFamilySize_Pic);
            $maxFamilySize  = $maxFamilySize_Text;
            //
            // Check that the family entry will fit onto the current page
            //


            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////


            if (($y-$maxFamilySize)<$intMinBottomPageY){
                // insert new pagge
                // reset top values
                if($intPageCount == (@$_GET['StartPageNum']-1))
                {
                    // insert titlepage
                    if($bShowTitlePage ) {
                        if(trim($Indv_sql)=="TRUE") {
                            $Indv_sql_ = "n/a";
                        }else {
                            $pos = strspn($Indv_sql, "TRUE   AND");
                            $Indv_sql_ = substr($Indv_sql,$pos);
                        }
                        if(trim($Fmly_sql)=="TRUE") {
                            $Fmly_sql_ = "n/a";
                        }else {
                            $pos = strspn ($Fmly_sql, "TRUE   AND");
                            $Fmly_sql_ = substr($Fmly_sql,$pos);
                        }

                        // title page
                        $intPageCount++;
                    }
                    // don't end page
                } else
                {
                    // Middle footer
                    if($intPageSize==2){
                        //							pdf_end_page($pdf);
                    }
                }

                if($intPageSize==2){

                    // start a new page (A4)
                    $intPageCount++;
                    // reset X,Y values to defaults
                    $y = $intTopOfPageY;
                    $x = $intTopOfPageX;
                    // insert new top line for page 1
                    $y = $y - $intLineSepSize;
                    $x = $intPage1LeftX;
                    $intPageSize = 1;
                } else {
                    // start next side of page
                    $intPageCount++;
                    $intPageSize=2;
                    $y = $intTopOfPageY;
                    $x = $intPage2LeftX;
                    // insert new top line for page 2
                    $y = $y - $intLineSepSize;
                }
            }
            else
            {
                // then OK to print
            }

            // SHOW FAMILY NAME

            $pageFamilyId[$intPageCount][$FamilyId] = "Family: $Indv_FamilyShortName";
            //if ($bDebug) echo "\n<p> pageFamilyId[".$intPageCount."][".$FamilyId."] = Family: ".$Indv_FamilyShortName." <p>\n";

            // SHOW HOME PHONE
            $intTopOfAddressY = $y-$HomeAddrHeightY-10;
            // SHOW HOME ADDRESS

            if (strlen($Fmly_PostalAddress)>0){

                $intTopOfAddressY = $y-$HomeAddrHeightY-$HomeAddrHeightY-10;
            }
            //
            // now display image
            //
            if ($bImage == TRUE AND $bShowFamilyPicture ) {

            } else
            {
                $bottom_image_Y = $intTopOfAddressY ;
            }
            // remove of temp files

            $sql_Indv = "SELECT * FROM (((Individual) LEFT JOIN Gender ON ".$PACTS_cfg->individualtablename.".GenderCode = Gender.GenderCode) LEFT  JOIN Title ON ".$PACTS_cfg->individualtablename.".Title = Title.Title) LEFT  JOIN RoleType ON ".$PACTS_cfg->individualtablename.".RoleTypeCode = RoleType.RoleTypeCode WHERE ".$PACTS_cfg->individualtablename.".FamilyId=$FamilyId AND  $Indv_sql   AND ".$PACTS_cfg->individualtablename.".RoleTypeCode = 'Head Of Family' ORDER BY ".$PACTS_cfg->individualtablename.".RoleTypeCode DESC, ".$PACTS_cfg->individualtablename.".GenderCode DESC;";

            $result_Indv = $PACTS_cfg->LogQuery($sql_Indv,__LINE__,__FILE__);

            // insert a seperator row
            $RoleY = -1;
            // Head Of Family Loop
            while ($row_Indv = mysql_fetch_array($result_Indv)) {

                //
                // Print Individual
                //

                $Indv_id = $row_Indv["IndividualId"];
                $Indv_FirstName = $row_Indv["FirstName"];
                if(strlen(trim($row_Indv["ShortName"]))>0) {
                    $Indv_FirstName = $row_Indv["ShortName"];
                }
                $Indv_Surname = $row_Indv["Surname"];
                $Indv_IndividualPhoto = $row_Indv["IndividualPhoto"];
                if($bShowRole) {
                    $Indv_role= $row_Indv["RoleTypeCode"];
                } else {
                    $Indv_role= "";
                }
                if($bShowGender) {
                    $Indv_Gender = $row_Indv;
                } else {
                    $Indv_Gender = "";
                }

                if(($bHidePrivateData && $row_Indv["MobilePhonePrivateIndicator"]=="Y") || $bShowMobilePhoneNumber==FALSE) {
                    $Indv_MobilePhoneNum = "";
                } else {
                    $Indv_MobilePhoneNum = $row_Indv["MobilePhoneNumber"];
                }

                if(($bHidePrivateData && $row_Indv["WorkPhonePrivateIndicator"]=="Y") || $bShowWorkPhoneNumber==FALSE) {
                    $Indv_WorkPhoneNum = "";
                } else {
                    $Indv_WorkPhoneNum = $row_Indv["WorkPhoneNumber"];
                }

                if(($bHidePrivateData && $row_Indv["HomeEmailAddressPrivateIndicator"]=="Y") || $bShowHomeEmailAddress==FALSE) {
                    $Indv_HomeEmail = "";
                } else {
                    $Indv_HomeEmail = $row_Indv["HomeEmailAddress"];
                }
                if(($bHidePrivateData && $row_Indv["WorkEmailAddressPrivateIndicator"]=="Y") || $bShowWorkEmailAddress==FALSE) {
                    $Indv_WorkEmail = "";
                } else {
                    $Indv_WorkEmail = $row_Indv["WorkEmailAddress"];
                }
                if($bShowSchoolGrade) {
                    $Indv_SchoolGrade = $row_Indv["KindergartenCommenceYear"];
                } else {
                    $Indv_SchoolGrade = "";
                }
                if ($row_Indv["RoleTypeCode"] == "Head Of Family"){
                    $HeadOfFamilyCount = $HeadOfFamilyCount + 1;
                    $roleX = $x+$intFirstNameIndentX+($intLeftEmailDetailsIndentX-$intFirstDetailsX+$intSpaceBetweenHofX )*($HeadOfFamilyCount-1);
                    $origY = $y;

                    ////////////// SHOW FOR HOF
                    // put a small space after the HOF names and phone nums
                    $y = $y - 4;


                    if(!is_null($Indv_WorkPhoneNum) and strlen($Indv_WorkPhoneNum)>0) {
                        $y = $y - $intSmallLineSepSize;
                        // SHOW WORK PHONE
                    }
                    if(!is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)>0) {
                        $y = $y - $intSmallLineSepSize;
                        // SHOW MOBILE PHONE
                    }
                    if(!is_null($Indv_WorkEmail) and strlen($Indv_WorkEmail)>0) {
                        $y = $y - $intSmallLineSepSize;
                        // SHOW WORK EMAIL
                    }
                    if(!is_null($Indv_HomeEmail) and strlen($Indv_HomeEmail)>0) {
                        $y = $y - $intSmallLineSepSize;
                        // SHOW HOME EMAIL
                    }

                    if($RoleY==-1) {
                        $RoleY = $y;
                    }
                    if ($y < $RoleY) {
                        $RoleY = $y;
                    }
                    $y = $origY;

                    ////////////// END SHOW FOR HOF
                } // end HOF if
                // MOVE TO NEXT INDV


            } // end Head Of Family Loop

            $sql_Indv = "SELECT * FROM (((Individual) LEFT JOIN Gender ON ".$PACTS_cfg->individualtablename.".GenderCode = Gender.GenderCode) LEFT  JOIN Title ON ".$PACTS_cfg->individualtablename.".Title = Title.Title) LEFT  JOIN RoleType ON ".$PACTS_cfg->individualtablename.".RoleTypeCode = RoleType.RoleTypeCode WHERE ".$PACTS_cfg->individualtablename.".FamilyId=$FamilyId AND  $Indv_sql   AND  ".$PACTS_cfg->individualtablename.".RoleTypeCode <> 'Head Of Family' ORDER BY KindergartenCommenceYear ASC;";

            //echo "SQL : $sql_Indv ";

            $result_Indv = $PACTS_cfg->LogQuery($sql_Indv,__LINE__,__FILE__);

            // start Children/Others Individual Loop
            while ($row_Indv = mysql_fetch_array($result_Indv)) {
                $Indv_id = $row_Indv["IndividualId"];
                $Indv_FirstName = $row_Indv["FirstName"];
                if(strlen(trim($row_Indv["ShortName"]))>0) {
                    $Indv_FirstName = $row_Indv["ShortName"];
                }
                $Indv_Surname = $row_Indv["Surname"];
                $Indv_IndividualPhoto = $row_Indv["IndividualPhoto"];
                if($bShowRole) {
                    $Indv_role= $row_Indv["RoleTypeCode"];
                } else {
                    $Indv_role= "";
                }
                if($bShowGender) {
                    $Indv_Gender = $PACTS_cfg->getLookValue("Gender", "GenderCode", $row_Indv["GenderCode"], "Description");
                } else {
                    $Indv_Gender = "";
                }

                if(($bHidePrivateData && $row_Indv["MobilePhonePrivateIndicator"]=="Y") || $bShowMobilePhoneNumber==FALSE) {
                    $Indv_MobilePhoneNum = "";
                } else {
                    $Indv_MobilePhoneNum = $row_Indv["MobilePhoneNumber"];
                }

                if(($bHidePrivateData && $row_Indv["WorkPhonePrivateIndicator"]=="Y") || $bShowWorkPhoneNumber==FALSE) {
                    $Indv_WorkPhoneNum = "";
                } else {
                    $Indv_WorkPhoneNum = $row_Indv["WorkPhoneNumber"];
                }

                if(($bHidePrivateData && $row_Indv["HomeEmailAddressPrivateIndicator"]=="Y") || $bShowHomeEmailAddress==FALSE) {
                    $Indv_HomeEmail = "";
                } else {
                    $Indv_HomeEmail = $row_Indv["HomeEmailAddress"];
                }
                if(($bHidePrivateData && $row_Indv["WorkEmailAddressPrivateIndicator"]=="Y") || $bShowWorkEmailAddress==FALSE) {
                    $Indv_WorkEmail = "";
                } else {
                    $Indv_WorkEmail = $row_Indv["WorkEmailAddress"];
                }
                if($bShowSchoolGrade) {
                    $Indv_SchoolGrade = $PACTS_cfg->getSchoolGrade($row_Indv["KindergartenCommenceYear"],$bShowSchoolGrade,$bShowYA,$row_Indv["YoungAdultIndicator"])."a";
                } else {
                    $Indv_SchoolGrade = "";
                }

                if ($HeadOfFamilyCount > 0) {
                    if($RoleY==-1) {
                        $RoleY = $y;
                    }
                    $y = $RoleY - $intLineSepSize;
                    $HeadOfFamilyCount = 0;
                    $RoleY = -1;
                }
                // SHOW FIRSTNAME

                $tmpstr ="";
                if($bShowGender) {
                    $tmpstr = "$Indv_Gender ";
                }
                if($bShowRole) {
                    $tmpstr = trim($tmpstr)." $Indv_role ";
                }
                $tmpstr = trim($tmpstr);
                // SHOW ROLE
                if(strlen($Indv_SchoolGrade)>0) {
                    if (strlen($tmpstr)>0){
                        $tmpstr = $tmpstr." in ";
                    }
                    $tmpstr = "(".$tmpstr."$Indv_SchoolGrade)";
                }else
                {
                    if(strlen($tmpstr)>0) {

                    }
                }


                $y_tmp = $y;
                $y_tmp2 = $y;

                $tmp_pos = 1;
                $tmp_posTxt[1] = "";
                $tmp_posTxt[2] = "";
                $tmp_posTxt[3] = "";
                $tmp_posTxt[4] = "";

                if(!is_null($Indv_WorkPhoneNum) and strlen($Indv_WorkPhoneNum)>0) {
                    $y_tmp = $y_tmp - $intSmallLineSepSize;
                    // SHOW WORK PHONE
                    $tmp_posTxt[$tmp_pos] = "W:$Indv_WorkPhoneNum";
                    $tmp_pos++;
                }
                if(!is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)>0) {
                    $y_tmp = $y_tmp - $intSmallLineSepSize;
                    // SHOW MOBILE PHONE
                    $tmp_posTxt[$tmp_pos] = "M:$Indv_MobilePhoneNum";
                    $tmp_pos++;
                }
                if(!is_null($Indv_WorkEmail) and strlen($Indv_WorkEmail)>0) {
                    $y_tmp2 = $y_tmp2 - $intSmallLineSepSize;
                    $tmp_posTxt[$tmp_pos] = "W:$Indv_WorkEmail";
                    $tmp_pos++;


                    // SHOW WORK EMAIL
                    if(is_null($Indv_WorkPhoneNum) || strlen($Indv_WorkPhoneNum)==0 || is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)==0) {
                    } else {
                    }
                }
                if(!is_null($Indv_HomeEmail) and strlen($Indv_HomeEmail)>0) {
                    $y_tmp2 = $y_tmp2 - $intSmallLineSepSize;
                    // SHOW HOME EMAIL
                    $tmp_posTxt[$tmp_pos] = "H:$Indv_HomeEmail";
                }

                $tmp_pos = 1;
                while (strlen($tmp_posTxt[$tmp_pos])>0){

                    if ($tmp_pos==1){

                        $tmpx=$x+$intFirstDetailsX;
                        $tmpy=$y-$intSmallLineSepSize;
                    }
                    if ($tmp_pos==2){
                        $tmpx=$x+$intLeftEmailDetailsIndentX+50;
                        $tmpy=$y-$intSmallLineSepSize;
                    }
                    if ($tmp_pos==3){
                        $tmpx=$x+$intFirstDetailsX;
                        $tmpy=$y-$intSmallLineSepSize-$intSmallLineSepSize;
                    }
                    if ($tmp_pos==4){
                        $tmpy=$y-$intSmallLineSepSize-$intSmallLineSepSize;
                        $tmpx=$x+$intLeftEmailDetailsIndentX+50;
                    }

                    $tmp_pos++;
                }



                $y = $y_tmp2;
                if($y > $y_tmp) {
                    $y = $y_tmp;
                }
                // insert a seperator row
                $y = $y - $intLineSepSize;

            } // end Children/Others Individual Loop
            $y = $y - $intLineSepSize;

            if($y > $bottom_image_Y ) {
                $y = $bottom_image_Y - $intMinSepAfterAddrY;
                $bottom_image_Y = $y;
            } else {
                if ( $y > ($intTopOfAddressY ) )
                {
                    $y = $intTopOfAddressY;//- $intMinSepAfterAddrY;
                } else {
                    $y = $y + 20;
                }
            }
            //
            // Insert line at end of Family
            //

            if($intPageSize==1){
                $y = $y - $intLineSepSize;
            } else {
                $y = $y - $intLineSepSize;
            }
        } // end if count family
    } // end while family
} // end if rowcount //if($resultsnumber_Fmly >0)

if(	$intPageCount == (@$_GET['StartPageNum']-1)){
    // family row count is zero
    // insert titlepage
    if($bShowTitlePage ) {
        if(trim($Indv_sql)=="TRUE") {
            $Indv_sql_ = "n/a";
        }else {
            $pos = strspn($Indv_sql, "TRUE   AND");
            $Indv_sql_ = substr($Indv_sql,$pos);
        }
        if(trim($Fmly_sql)=="TRUE") {
            $Fmly_sql_ = "n/a";
        }else {
            $pos = strspn ($Fmly_sql, "TRUE   AND");
            $Fmly_sql_ = substr($Fmly_sql,$pos);
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////////////////////////////////////////////
        $intPageCount++;
    } // end show titlepage
    $intPageCount++;
} // end if	
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//print $intPageCount." Pages";

///////////////////////////
/// from Algo
///////////////////////////

$numpages =$intPageCount ;
$maxpages = $numpages;
if ($numpages % 4 != 0){
    $maxpages += (4-$numpages % 4);
}

for ($i=0; $i<$numpages; $i++){
    $pages[$i] = $i+1;
}
for ($i=$numpages; $i<$maxpages; $i++){
    $pages[$i] = "blank";
}

$min = 0; 
$max = $maxpages-1; 
$thissheet = 0;
//echo "\nPrinting order for ".$numpages." $pages:<br />\n\n";
for ($i=0; $i<$maxpages; $i+=4)
{
    $thissheet++;
    $left = $pages[$max--];
    $pageOrder[$left] = "L".$thissheet;
    $right = $pages[$min++];
    $pageOrder[$right] = "R".$thissheet;
    if ($bDebug) 	echo "Sheet ".$thissheet.", front: ".$left.", ".$right."<br />\n";
    if ($numpages == 1) break;
    $thissheet++;
    $left = $pages[$min++];
    $pageOrder[$left] = "L".$thissheet;
    $right = $pages[$max--];
    $pageOrder[$right] = "R".$thissheet;
    if ($bDebug)	echo "Sheet ".$thissheet.", back : ".$left.", ".$right."<br />\n";
}

if ($bDebug)echo "\n<p>Number of sheets = ".$thissheet."<p>\n";

for ($i=1; $i<$maxpages+1; $i++){
    if ($bDebug)		echo "<br />Booklet Original page ".$i." on Actual Physical ".@$pageOrder[$i]."";

}
///////////////////////////
/// End Algo
///////////////////////////
if ($bDebug){
    //	echo "\n-<p>\n";
    //	print_r($pageFamilyId);
    //	echo "\n<p>-\n";
}
if ($bDebug)        echo "<p>\n";

if ($bDebug)        echo "<p>\n";
/*
foreach ($pageFamilyId as $v1=>$OriginalPageNumber1) {
    foreach ($OriginalPageNumber1 as $v2=>$OriginalPageNumber2) {
// if ($bDebug) print " \$pageFamilyId [$v1] [$v2]  : $OriginalPageNumber2<br />\n";
    }
}

*/
if ($bDebug)        echo "<p>\n";





if ($bDebug)     
{
    print_r($pageFamilyId);
    print "<hr>";
    print "<hr>";
    print "<hr>";
    print "<hr>";
}






///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Start actual produce PDF 	

if ($bDebug)        echo "<h1>Start actual produce PDF : Line ".__LINE__."</h1>\n";


$sql_Fmly = "SELECT ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyPhoto, ".$PACTS_cfg->familytablename.".FamilyShortName FROM (Individual INNER JOIN Family ON ".$PACTS_cfg->individualtablename.".FamilyId = ".$PACTS_cfg->familytablename.".FamilyId) WHERE $Indv_sql AND $Fmly_sql GROUP BY ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyPhoto, ".$PACTS_cfg->familytablename.".FamilyShortName ORDER BY ".$PACTS_cfg->familytablename.".FamilyShortName ASC";

$result_Fmly = $PACTS_cfg->LogQuery($sql_Fmly,__LINE__,__FILE__);
$resultsnumber_Fmly = 0;
$resultsnumber_Fmly = @mysql_num_rows($result_Fmly);


//	$pdf = pdf_new();

// open a file & save it to specified location
//pdf_open_file($pdf, "philosophy.pdf");

if (!pdf_open_file($pdf, "")) {
    print error;
    exit;
};
pdf_set_parameter($pdf, "warning", "true");

pdf_set_info($pdf, "Author", $PACTS_cfg->SoftwareLongName." ");
pdf_set_info($pdf, "Title", (isset($_GET['view'])) ? " " : $_GET['view'] ) ;
pdf_set_info($pdf, "Creator", @$_SESSION['username']." ");
pdf_set_info($pdf, "Subject", (isset($_GET['view'])) ? " " : $_GET['view'] ) ;

// get and use a font object

$NormalPDFFont_bold  = PDF_findfont($pdf,$BoldFont,"host",0);
$Helvetica  = PDF_findfont($pdf,$NormalFont,"host",0);
$NormalPDFFont = $Helvetica;

PDF_set_parameter($pdf, "openaction", "fitwidth");
//	PDF_set_parameter($pdf, "openaction", "fitpage");
PDF_set_parameter($pdf, "openmode", "none");


// initialise variables for start
$y = $intMinBottomPageY-1 ; // set over limit so that new page (page1) will be inserted
$prevy=$y;
$x = $intTopOfPageX;
$intPageCount = @$_GET['StartPageNum']-1; // set count to 0
$ActualIntPageCount = 1;


//pdf_setfont($pdf, $NormalPDFFont, 20);
//pdf_show_xy($pdf, "Number of results : $resultsnumber", $x, $y+15);

if($resultsnumber_Fmly >0) {
    //		echo mysql_num_rows($result_Fmly)."<p>";
    if ($bDebug)        echo "<h2>While each Family : Line ".__LINE__."</h2>\n";


    /// insert title page

    // insert titlepage
    if($bShowTitlePage) {
        if(trim($Indv_sql)=="TRUE") {
            $Indv_sql_ = "n/a";
        }else {
            $pos = strspn($Indv_sql, "TRUE   AND");
            $Indv_sql_ = substr($Indv_sql,$pos);
        }
        if(trim($Fmly_sql)=="TRUE") {
            $Fmly_sql_ = "n/a";
        }else {
            //							$Fmly_sql_ = $Fmly_sql;
            $pos = strspn ($Fmly_sql, "TRUE   AND");
            $Fmly_sql_ = substr($Fmly_sql,$pos);
        }

        //printPDFTitlePage($pdf, "Church Directory", "Filtered by : (Indv) ".$Indv_sql_." and (Fmly) ".$Fmly_sql_, $intPageSizeX , $intPageSizeY, $intTopOfPageX, $intTopOfPageY, $intMinBottomPageY, $NormalPDFFont,$NormalPDFFont_bold,0, $intPageSizeY/($intPageSizeX/$intPageSizeY), $intPageSizeY  );
        //$intPageCount++;
        //	$ActualIntPageCount++;
        $bShowTitlePage = FALSE;
    }
    // don't end page





    //echo "<p>START PDF<p><p>";


    $strPageLocator = "R";
    $PhysicalPageNumber = 0;
    $intPageCount=0;
    $PhysicalPageNumber_old = 0;
    $bFirstPage = TRUE;

    //	while(strlen($pageOrder[$ActualIntPageCount])>0){
    while( $ActualIntPageCount <= $maxpages){

        if(	$strPageLocator == "R"){
            $strPageLocator = "L";
            $PhysicalPageNumber++;
        } else {
            $strPageLocator = "R";
            $PhysicalPageNumber = $PhysicalPageNumber;
        }
        $OriginalPageNumber=0;

        if ($bDebug)	echo "\n---------------------------------------------------------------------------<br />\n";
        if ($bDebug)	echo "Finding : strPageLocator = $strPageLocator, PhysicalPageNumber = $PhysicalPageNumber\n<br />";
        while (	substr(@$pageOrder[$OriginalPageNumber],0,1) != $strPageLocator || substr(@$pageOrder[$OriginalPageNumber],1) != $PhysicalPageNumber)
        {
            //		echo "k=$OriginalPageNumber - ".substr($pageOrder[$OriginalPageNumber],0,1)." -- ".substr($pageOrder[$OriginalPageNumber],1)."\n<br />";
            $blankpage = FALSE;
            if ($OriginalPageNumber> $maxpages) {
                //			echo "at max ending";
                $blankpage = TRUE;
                break;
            }
            $OriginalPageNumber++;
        }// end while

        if ($bDebug)	echo "OriginalPageNumber = $OriginalPageNumber \n<br />";
        //		if ($bDebug)	print_r($pageOrder);

        $strLR = substr(@$pageOrder[$OriginalPageNumber],0,1);
        $strNum = substr(@$pageOrder[$OriginalPageNumber],1);

        if ($strLR=="R" and $strNum==1){
            //		@pdf_begin_page($pdf, $intPageSizeX , $intPageSizeY );
        }

        if ($bDebug) echo "<br />\nstrLR = $strLR - strNum = $strNum<br />\n";


        if (FALSE) {
            pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
            if ($strLR=="L"){
                pdf_show_xy($pdf, "strLR = $strLR - strNum = $strNum", $intPage2MidX-10, $intPageCountPosY+20);
            } else
            {
                pdf_show_xy($pdf, "strLR = $strLR - strNum = $strNum", $intPage1MidX-10, $intPageCountPosY+20);
            }

        }

        $pageFamily = "";


        foreach ($pageFamilyId as $v1=>$OriginalPageNumber1) {
            foreach ($OriginalPageNumber1 as $v2=>$OriginalPageNumber2) {
                if ($v1==$OriginalPageNumber){
                    if ($bDebug) print " \$pageFamilyId [$v1][$v2] = $OriginalPageNumber2             :: $strNum <br />\n";
                    $pageFamily = $pageFamily." Family.FamilyId = $v2 OR ";
                }
            }
        }// end foreach

        if (strlen(trim($pageFamily))>0){
            $pageFamily = $pageFamily." FALSE ";
        } else{
            $pageFamily = "TRUE";
        }


        if ($bDebug)		echo "<p>Page Family = ".$pageFamily."...... blankpage = $blankpage\n : Line ".__LINE__."<br>\n";

        ////////////////////////////////////////////////////////////////////////////////////
        if (TRUE){
            $sql_Fmly = "SELECT ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyPhoto, ".$PACTS_cfg->familytablename.".FamilyShortName FROM (Individual INNER JOIN Family ON ".$PACTS_cfg->individualtablename.".FamilyId = ".$PACTS_cfg->familytablename.".FamilyId) WHERE $Indv_sql AND $Fmly_sql AND ($pageFamily) GROUP BY ".$PACTS_cfg->familytablename.".FamilyId, ".$PACTS_cfg->familytablename.".FamilyPhoto, ".$PACTS_cfg->familytablename.".FamilyShortName ORDER BY ".$PACTS_cfg->familytablename.".FamilyShortName ASC";

            $result_Fmly = $PACTS_cfg->LogQuery($sql_Fmly,__LINE__,__FILE__);

            if ($bDebug)		echo "<br />\n<br />\nsql_Fmly = '$sql_Fmly'<br />\n<br />\n";

            //	echo "\nPhysicalPageNumber_old  = $PhysicalPageNumber_old,  PhysicalPageNumber  =$PhysicalPageNumber\n";
            if ($PhysicalPageNumber_old < $PhysicalPageNumber){
                // start a new page (A4)
                if(!$bFirstPage){
                    //	echo "\nending page\n";

                    if (!$bDebug) pdf_end_page($pdf);
                }
                $bFirstPage = FALSE;
                //	echo "\nstarting new page\n";
                if (!$bDebug)	{
                    pdf_begin_page($pdf, $intPageSizeX , $intPageSizeY );
                    $bPage_Open = TRUE;
                }
                $PhysicalPageNumber_old = $PhysicalPageNumber;
            }

            //					echo "<p> pageOrder =  $pageOrder[$ActualIntPageCount] <p>";

            $y = $intTopOfPageY;
            if (!$bDebug){
                if 	($strLR  == "R"){
                    // start next side of page
                    //$intPageCount++;
                    $intPageSize=2;
                    $x = $intPage2LeftX; // RIGHT PART OF PAGE
                    // insert new top line for page 2
                    if (!$blankpage){
                        PDF_moveto($pdf,$intPage2LeftX  ,$y+4 );
                        PDF_lineto($pdf,$intPage2RightX,$y+4 );
                        PDF_stroke($pdf);
                    }
                    pdf_setfont($pdf, $NormalPDFFont, $smallmediumFontSize);
                    $PACTS_cfg->printFooterText($pdf, $OriginalPageNumber, $intPage2MidX ,$NormalPDFFont, $smallmediumFontSize,$intPageCountPosY ,$bShowPageFooter,$bShowPageNumber,$bDebug);
                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                    $y = $y - $intLineSepSize;
                }
                if 	($strLR  == "L"){
                    //							$intPageCount++;
                    // reset X,Y values to defaults
                    $x = $intPage1LeftX;  // LEFT PART OF PAGE
                    if (!$blankpage){
                        // insert new top line for page 1
                        PDF_moveto($pdf,$intPage1LeftX  ,$y+4 );
                        PDF_lineto($pdf,$intPage1RightX,$y+4 );
                        PDF_stroke($pdf);
                    }
                    $y = $y - $intLineSepSize;
                    $intPageSize = 1;
                    pdf_setfont($pdf, $NormalPDFFont, $smallmediumFontSize);
                    $PACTS_cfg->printFooterText($pdf, $OriginalPageNumber, $intPage1MidX,$NormalPDFFont, $smallmediumFontSize,$intPageCountPosY,$bShowPageFooter,$bShowPageNumber,$bDebug);
                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                }
            } else {

                    $PACTS_cfg->printFooterText($pdf, $OriginalPageNumber, $intPage1MidX,$NormalPDFFont, $smallmediumFontSize,$bShowPageFooter,$intPageCountPosY,$bShowPageNumber,$bDebug);

            }


            while ($row_Fmly = mysql_fetch_array($result_Fmly) and !$blankpage) {
                $y = $y - 5; // a small separator
                //
                // Grab Family details
                //
                $HeadOfFamilyCount = 0;

                if ($bDebug)        echo "<h2>While each FamilyId = ".$row_Fmly["FamilyId"]." : Line ".__LINE__."</h2>\n";
                $FamilyId = $row_Fmly["FamilyId"];

                //			   $sql_SingleFmly = "SELECT * FROM Family WHERE FamilyId= $FamilyId;";
                //			   $result_SingleFmly = mysql_query($sql_SingleFmly);
                //			   $row_SingleFmly = mysql_fetch_array($result_SingleFmly);

                $row_SingleFmly = $array[$FamilyId];

                // count the number of members in family
                //$sql_Indvcnt = "SELECT COUNT(*) as Fmly_Indvcnt FROM Individual WHERE FamilyId = $FamilyId AND $Indv_sql ;";

                //			echo "sql_Indvcnt :: $sql_Indvcnt <p>";

                //				$result_Fmly_Indvcnt = $PACTS_cfg->LogQuery($sql_Indvcnt,__LINE__,__FILE__ );
                //				$row_Fmly_Indvcnt = mysql_fetch_array($result_Fmly_Indvcnt);
                $Fmly_Indvcnt = $row_Fmly_Indvcnt[$FamilyId];
                //			echo "FamilyID = $FamilyId   $Fmly_Indvcnt  members<p>";

                if ($bDebug)        echo "<h3> Fmly_Indvcnt= ".$Fmly_Indvcnt." : Line ".__LINE__."</h3>\n";

                $Indv_FamilyShortName = "";
                $Fmly_ResAddress = "";
                $Fmly_PostalAddress = "";
                $Fmly_HomePhone = "";


                if($Fmly_Indvcnt>0) {
                    $Indv_FamilyShortName = $PACTS_cfg->getFormattedFamilyShortName($FamilyId," ");

                    if($row_SingleFmly["ResidentialAddressPrivateIndicator"]=="Y" and $bHidePrivateData) {
                        $Fmly_ResAddress = "";
                    } else {
                        $Fmly_ResAddress  = $PACTS_cfg->getFormattedResidentialAddress($FamilyId, chr(10),TRUE,FALSE,FALSE,FALSE ,FALSE , "", $bShowPrivateResidentialAddressesAsXXX, FALSE);

                    }

                    if($row_SingleFmly["MailingAddressIndicator"]=="N" and strlen($row_SingleFmly["PostalAddressLine1"])>0 ) {

                        $Fmly_PostalAddress = $PACTS_cfg->getFormattedPostalAddress($FamilyId, chr(10),TRUE,FALSE,FALSE,FALSE ,
                               " ");

                    } else {
                        $Fmly_PostalAddress = "";

                    }


                    if (strlen(trim($Fmly_ResAddress))==0 and strlen(trim($Fmly_PostalAddress))>0){
                        $Fmly_ResAddress = $Fmly_PostalAddress ;
                        $Fmly_PostalAddress = "";
                    }


                    if($row_SingleFmly["HomePhoneNumberPrivateIndicator"]=="Y" and $bHidePrivateData) {
                        $Fmly_HomePhone = "";
                    } else {
                        $Fmly_HomePhone     = $PACTS_cfg->getFormattedHomePhoneNumber($FamilyId," ",FALSE, FALSE, FALSE, "",  $bShowPrivateTelephoneNumbersAsXXX);
                    }
                    $Fmly_Photo = $row_Fmly["FamilyPhoto"];

                    /////////////////// Create tmp file //////////////////////////
                    if (strlen($Fmly_Photo) > 0){
                        $tt = explode( " ", microtime());
                        //	echo("random : ".(int)($tt[0] * time())."<p>");

                        $filename = "".(int)($tt[0] * time()).".jpg";
                        $handle = fopen($filename, 'wb');
                        if (!$handle) {
                            print "Cannot open file ($filename)";
                            exit;
                        }


                        //echo "len Fmly_Photo = $Fmly_Photo <P>";
                        //exit;

                        // Write $somecontent to our opened file.
                        $bImage = FALSE;
                        $pdf_im_width = 0;
                        $pdf_im_height = 0;
                        $pdf_im_ratio = 0;
                        if(!is_null($Fmly_Photo) and strlen($Fmly_Photo)>0 ) {
                            if (!fwrite($handle, $Fmly_Photo)) {
                                print "Cannot write to file ($filename)";
                                exit;
                            }
                            else
                            {
                                $bImage = TRUE;
                                $pim = pdf_open_image_file($pdf, "jpeg", $filename);
                                $pdf_im_width = pdf_get_value($pdf, "imagewidth", $pim);
                                $pdf_im_height = pdf_get_value($pdf, "imageheight", $pim);

                                // $intImageWidth
                                $pdf_im_ratio = (double)$intImageWidth/$pdf_im_width;
                            }
                        }
                        else
                        {
                            $bottom_image_Y = 100000;
                        }
                    } else
                    {
                        $bImage = FALSE;
                    }
                    /////////////////// End Get Image //////////////////////////


                    $maxFamilySize_Text = $intSmallLineSepSize*2*$Fmly_Indvcnt+10; // was 50
                    if (strlen($Fmly_PostalAddress)>0) {
                        $maxFamilySize_Text = $maxFamilySize_Text + $intPostalAddressSizeY;
                    }

                    $maxFamilySize_Pic = ((int) @$pdf_im_height * @$pdf_im_ratio)+0; // was 50

                    $maxFamilySize = max($maxFamilySize_Text, $maxFamilySize_Pic);

                    //
                    // Check that the family entry will fit onto the current page
                    //

                    if (($y-$maxFamilySize)<$intMinBottomPageY){
                        // insert new pagge
                        // reset top values
                        if($intPageCount == (@$_GET['StartPageNum']-1))
                        {
                            // old insert title page
                        } else
                        {
                            // Middle footer
                            //pdf_setfont($pdf, $NormalPDFFont, 10);
                            if($intPageSize==2){
                                //								pdf_end_page($pdf);
                            }
                        }



                    }
                    else
                    {
                        // then OK to print
                        // $y = $y - $intLineSepSize;
                    }


                    if ($bDebug)
                    {
                    echo "about to print family/indv details :-<br>";
                    echo "Indv_FamilyShortName : $Indv_FamilyShortName<br>";
                    echo "Fmly_ResAddress : <pre>$Fmly_ResAddress</pre><br>";

                    }

                    if (!$bDebug){
//  $Indv_FamilyShortName = "XxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxX";
//$Indv_FamilyShortName  = $Fmly_HomePhone;
                        pdf_setfont($pdf, $NormalPDFFont_bold, $largeFontSize);
                        // SHOW FAMILY NAME
                        // Adjust font size if Indv_FamilyShortName is too long
                        PDF_create_bookmark($pdf, "$Indv_FamilyShortName Family","");
                        if (strlen($Indv_FamilyShortName)>12){
                            pdf_setfont($pdf, $NormalPDFFont_bold, $mediumlargeFontSize);
                        }
                        if (strlen($Indv_FamilyShortName)>13){
                            pdf_setfont($pdf, $NormalPDFFont_bold, $mediumlargeFontSize-1);
                        }
                        if (strlen($Indv_FamilyShortName)>15){
                            pdf_setfont($pdf, $NormalPDFFont_bold, $mediumlargeFontSize-2);
                        }
                        if (strlen($Indv_FamilyShortName)>19){
                            pdf_setfont($pdf, $NormalPDFFont_bold, $mediumlargeFontSize-4);
                        }
                        pdf_show_xy($pdf, "".$Indv_FamilyShortName."", $x, $y);
//                        pdf_show_xy($pdf, "xxxxxxxx", $x, $y);

                        // SHOW HOME PHONE
                        //				pdf_show_xy($pdf, "".$Fmly_HomePhone."", $x+$intHomeTelephoneIndentX, $y);
                        pdf_setfont($pdf, $NormalPDFFont_bold, $largeFontSize);

                        $nr = pdf_show_boxed($pdf, $Fmly_HomePhone, $x+$intHomeTelephoneIndentX-80, $y , 138, 12, "right","");


                        pdf_setfont($pdf, $NormalPDFFont, $smallmediumFontSize);
                        $intTopOfAddressY = $y-$HomeAddrHeightY-10;
                        // SHOW HOME ADDRESS

                        if (strlen($Fmly_ResAddress)>0){
                            $nr = pdf_show_boxed($pdf, $Fmly_ResAddress, $x, $intTopOfAddressY , 160, $HomeAddrHeightY, "left","");
                        }
                        if (strlen($Fmly_PostalAddress)>0){
                            $nr = pdf_show_boxed($pdf, $Fmly_PostalAddress, $x, $intTopOfAddressY-40  , 160, $HomeAddrHeightY, "left","");
                            $intTopOfAddressY = $y-$HomeAddrHeightY-$HomeAddrHeightY-10;
                        }
                        //
                        // now display image
                        //
                        if ($bImage == TRUE AND $bShowFamilyPicture ) {
                            //$pdf_im_ratio = 0.1;
                            $bottom_image_Y = $intTopOfAddressY + 10 - ((int) $pdf_im_height * $pdf_im_ratio);
                            // SHOW PHOTO
                            $pim = pdf_open_image_file($pdf, "jpeg", $filename);

                            $pdf_im_width = pdf_get_value($pdf, "imagewidth", $pim);
                            $pdf_im_height = pdf_get_value($pdf, "imageheight", $pim);

                            // $intImageWidth
                            $pdf_im_ratio = (double)$intImageWidth/$pdf_im_width;

                            $bottom_image_Y = $intTopOfAddressY + 10 - ((int) $pdf_im_height * $pdf_im_ratio);
                            // SHOW PHOTO

                            pdf_place_image($pdf, $pim, $x, $intTopOfAddressY-((int)$pdf_im_height*$pdf_im_ratio)+17, $pdf_im_ratio );
                            pdf_close_image($pdf, $pim);
                            fclose($handle);
                            unlink($filename);
                        } else
                        {
                            $bottom_image_Y = $intTopOfAddressY ;
                        }
                        // remove of temp files
                    }
                    $sql_Indv = "SELECT * FROM (((".$PACTS_cfg->individualtablename.") LEFT JOIN ".$PACTS_cfg->gendertablename." ON ".$PACTS_cfg->individualtablename.".GenderCode = ".$PACTS_cfg->gendertablename.".GenderCode) LEFT  JOIN Title ON ".$PACTS_cfg->individualtablename.".Title = ".$PACTS_cfg->titletablename.".Title) LEFT  JOIN ".$PACTS_cfg->roletypetablename." ON ".$PACTS_cfg->individualtablename.".RoleTypeCode = ".$PACTS_cfg->roletypetablename.".RoleTypeCode WHERE ".$PACTS_cfg->individualtablename.".FamilyId=$FamilyId AND  $Indv_sql   AND ".$PACTS_cfg->individualtablename.".RoleTypeCode = 'Head Of Family' ORDER BY ".$PACTS_cfg->individualtablename.".RoleTypeCode DESC, ".$PACTS_cfg->individualtablename.".GenderCode DESC;";

                    //					   $result_Indv = $PACTS_cfg->LogQuery($sql_Indv,__LINE__,__FILE__);
                    $result_Indv = mysql_query($sql_Indv);

                    // insert a seperator row
                    //					$y = $y - $intSmallLineSepSize;
                    $RoleY = -1;
                    // Head Of Family Loop

                    while ($row_Indv = mysql_fetch_array($result_Indv)) {

                        if ($bDebug)		echo "<p><h3>In HOF loop : Line ".__LINE__."</h3>\n";
                        //
                        // Print Individual
                        //

                        $Indv_id = $row_Indv["IndividualId"];
                        $Indv_FirstName = $row_Indv["FirstName"];
                        if(strlen(trim($row_Indv["ShortName"]))>0) {
                            $Indv_FirstName = $row_Indv["ShortName"];
                        }
                        $Indv_Surname = $row_Indv["Surname"];

                        if ($bDebug)		echo "<p><h4>HOF :$Indv_FirstName  $Indv_Surname : Line ".__LINE__."</h4>\n";

                        $Indv_IndividualPhoto = $row_Indv["IndividualPhoto"];
                        if($bShowRole) {
                            $Indv_role= $row_Indv["RoleTypeCode"];
                        } else {
                            $Indv_role= "";
                        }
                        if($bShowGender) {
                            $Indv_Gender = $PACTS_cfg->getLookValue("Gender", "GenderCode", $row_Indv["GenderCode"], "Description");
                        } else {
                            $Indv_Gender = "";
                        }

                        if(($bHidePrivateData && $row_Indv["MobilePhonePrivateIndicator"]=="Y") || $bShowMobilePhoneNumber==FALSE) {
                            $Indv_MobilePhoneNum = "";
                        } else {
                            $Indv_MobilePhoneNum = $PACTS_cfg->getFormattedMobilePhoneNumber($row_Indv["IndividualId"]," ", FALSE, FALSE ,"", $bShowPrivateTelephoneNumbersAsXXX);
                        }

                        if(($bHidePrivateData && $row_Indv["WorkPhonePrivateIndicator"]=="Y") || $bShowWorkPhoneNumber==FALSE) {
                            $Indv_WorkPhoneNum = "";
                        } else {
                            $Indv_WorkPhoneNum = $PACTS_cfg->getFormattedWorkPhoneNumber($row_Indv["IndividualId"]," ",FALSE,FALSE,FALSE ,"", $bShowPrivateTelephoneNumbersAsXXX);
                        }

                        if(($bHidePrivateData && $row_Indv["HomeEmailAddressPrivateIndicator"]=="Y") || $bShowHomeEmailAddress==FALSE) {
                            $Indv_HomeEmail = "";
                        } else {
                            $Indv_HomeEmail = $PACTS_cfg->getEmailAddress($Indv_id ,"HOME",FALSE,"",$bShowPrivateEmailAddressesAsXXX);
                        }
                        if(($bHidePrivateData && $row_Indv["WorkEmailAddressPrivateIndicator"]=="Y") || $bShowWorkEmailAddress==FALSE) {
                            $Indv_WorkEmail = "";
                        } else {
                            $Indv_WorkEmail = $PACTS_cfg->getEmailAddress($Indv_id ,"WORK",FALSE,"",$bShowPrivateEmailAddressesAsXXX);
                        }
                        if($bShowSchoolGrade) {
                            $Indv_SchoolGrade = $PACTS_cfg->getSchoolGrade($row_Indv["KindergartenCommenceYear"],$bShowSchoolGrade,$bShowYA,$row_Indv["YoungAdultIndicator"]);
                        } else {
                            $Indv_SchoolGrade = "";
                        }
                        if (!$bDebug){
                            pdf_setfont($pdf, $NormalPDFFont, $mediumFontSize);

                            if ($row_Indv["RoleTypeCode"] == "Head Of Family"){
                                $HeadOfFamilyCount = $HeadOfFamilyCount + 1;
                                //pdf_show_xy($pdf, "$Indv_FirstName", $x+$intFirstNameIndentX, $y);

                                $roleX = $x+$intFirstNameIndentX+($intLeftEmailDetailsIndentX-$intFirstDetailsX+$intSpaceBetweenHofX)*($HeadOfFamilyCount-1);
                                $origY = $y;
                                //$RoleY = $y;
                                pdf_setfont($pdf, $NormalPDFFont_bold, $largeFontSize);
                                pdf_show_xy($pdf, "$Indv_FirstName", $roleX, $y);

                                // put a small space after the HOF names and phone nums
                                $y = $y - 4;

                                ////////////// SHOW FOR HOF

                                pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                                if(!is_null($Indv_WorkPhoneNum) and strlen($Indv_WorkPhoneNum)>0) {
                                    $y = $y - $intSmallLineSepSize;
                                    // SHOW WORK PHONE
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                                    pdf_show_xy($pdf, "W:$Indv_WorkPhoneNum", $roleX, $y);
                                }
                                if(!is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)>0) {
                                    $y = $y - $intSmallLineSepSize;
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                                    // SHOW MOBILE PHONE
                                    pdf_show_xy($pdf, "M:$Indv_MobilePhoneNum", $roleX, $y);
                                }
                                if(!is_null($Indv_WorkEmail) and strlen($Indv_WorkEmail)>0) {
                                    $y = $y - $intSmallLineSepSize;
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                                    if (strlen($Indv_WorkEmail)>25){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-0.5);
                                    }
                                    if (strlen($Indv_WorkEmail)>29){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-1);
                                    }
                                    if (strlen($Indv_WorkEmail)>32){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-1.5);
                                    }
                                    if (strlen($Indv_WorkEmail)>35){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-2);
                                    }
                                    // SHOW WORK EMAIL
                                    pdf_show_xy($pdf, "W:$Indv_WorkEmail" , $roleX , $y);
                                }
                                if(!is_null($Indv_HomeEmail) and strlen($Indv_HomeEmail)>0) {
                                    $y = $y - $intSmallLineSepSize;
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                                    if (strlen($Indv_HomeEmail)>25){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-0.5);
                                    }
                                    if (strlen($Indv_HomeEmail)>29){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-1);
                                    }
                                    if (strlen($Indv_HomeEmail)>32){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-1.5);
                                    }
                                    if (strlen($Indv_HomeEmail)>35){
                                        pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-2);
                                    }
                                    // SHOW HOME EMAIL
                                    pdf_show_xy($pdf, "H:$Indv_HomeEmail" , $roleX , $y);
                                }

                                pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);


                                if($RoleY==-1) {
                                    $RoleY = $y;
                                }
                                if ($y < $RoleY) {
                                    $RoleY = $y;
                                }
                                $y = $origY;
                            }
                            ////////////// END SHOW FOR HOF
                        } // end HOF if
                        // MOVE TO NEXT INDV


                    } // end Head Of Family Loop

                    $sql_Indv = "SELECT * FROM (((Individual) LEFT JOIN Gender ON ".$PACTS_cfg->individualtablename.".GenderCode = Gender.GenderCode) LEFT  JOIN Title ON ".$PACTS_cfg->individualtablename.".Title = Title.Title) LEFT  JOIN RoleType ON ".$PACTS_cfg->individualtablename.".RoleTypeCode = RoleType.RoleTypeCode WHERE ".$PACTS_cfg->individualtablename.".FamilyId=$FamilyId AND  $Indv_sql   AND  ".$PACTS_cfg->individualtablename.".RoleTypeCode <> 'Head Of Family' ORDER BY KindergartenCommenceYear ASC;";

                    //echo "SQL : $sql_Indv ";

                    //					  $result_Indv = $PACTS_cfg->LogQuery($sql_Indv,__LINE__,__FILE__);
                    $result_Indv = mysql_query($sql_Indv);

                    // start Children/Others Individual Loop
                    while ($row_Indv = mysql_fetch_array($result_Indv)) {
                        if ($bDebug)		echo "<p><h3>In Children/Others loop : Line ".__LINE__."</h3>\n";

                        $Indv_id = $row_Indv["IndividualId"];
                        $Indv_FirstName = $row_Indv["FirstName"];
                        if(strlen(trim($row_Indv["ShortName"]))>0) {
                            $Indv_FirstName = $row_Indv["ShortName"];
                        }
                        $Indv_Surname = $row_Indv["Surname"];

                        if ($bDebug)		echo "<p><h4>HOF :$Indv_FirstName  $Indv_Surname : Line ".__LINE__."</h4>\n";

                        $Indv_IndividualPhoto = $row_Indv["IndividualPhoto"];
                        if($bShowRole) {
                            $Indv_role= $row_Indv["RoleTypeCode"];
                        } else {
                            $Indv_role= "";
                        }
                        if($bShowGender) {
                            $Indv_Gender = $PACTS_cfg->getLookValue("Gender", "GenderCode", $row_Indv["GenderCode"], "Description");
                        } else {
                            $Indv_Gender = "";
                        }

                        if(($bHidePrivateData && $row_Indv["MobilePhonePrivateIndicator"]=="Y") || $bShowMobilePhoneNumber==FALSE) {
                            $Indv_MobilePhoneNum = "";
                        } else {
                            $Indv_MobilePhoneNum = $PACTS_cfg->getFormattedMobilePhoneNumber($row_Indv["IndividualId"]," ", FALSE, FALSE ,"", $bShowPrivateTelephoneNumbersAsXXX);
                        }

                        if(($bHidePrivateData && $row_Indv["WorkPhonePrivateIndicator"]=="Y") || $bShowWorkPhoneNumber==FALSE) {
                            $Indv_WorkPhoneNum = "";
                        } else {
                            $Indv_WorkPhoneNum = $PACTS_cfg->getFormattedWorkPhoneNumber($row_Indv["IndividualId"]," ",FALSE,FALSE,FALSE ,"", $bShowPrivateTelephoneNumbersAsXXX);
                        }

                        if(($bHidePrivateData && $row_Indv["HomeEmailAddressPrivateIndicator"]=="Y") || $bShowHomeEmailAddress==FALSE) {
                            $Indv_HomeEmail = "";
                        } else {
                            $Indv_HomeEmail = $PACTS_cfg->getEmailAddress($Indv_id ,"HOME",FALSE,"",$bShowPrivateEmailAddressesAsXXX);
                        }
                        if(($bHidePrivateData && $row_Indv["WorkEmailAddressPrivateIndicator"]=="Y") || $bShowWorkEmailAddress==FALSE) {
                            $Indv_WorkEmail = "";
                        } else {
                            $Indv_WorkEmail = $PACTS_cfg->getEmailAddress($Indv_id ,"WORK",FALSE,"",$bShowPrivateEmailAddressesAsXXX);
                        }
                        if($bShowSchoolGrade) {
                            $Indv_SchoolGrade = $PACTS_cfg->getSchoolGrade($row_Indv["KindergartenCommenceYear"],$bShowSchoolGrade,$bShowYA,$row_Indv["YoungAdultIndicator"]);
                        } else {
                            $Indv_SchoolGrade = "";
                        }

                        if ($HeadOfFamilyCount > 0) {
                            if($RoleY==-1) {
                                $RoleY = $y;
                            }
                            $y = $RoleY - $intLineSepSize;
                            $HeadOfFamilyCount = 0;
                            $RoleY = -1;
                        }
                        if (!$bDebug){
                            // SHOW FIRSTNAME
                            pdf_setfont($pdf, $NormalPDFFont_bold, $smallmediumFontSize);

                            pdf_show_xy($pdf, "$Indv_FirstName", $x+$intFirstNameIndentX, $y);

                            $tmpstr ="";
                            if($bShowGender) {
                                $tmpstr = "$Indv_Gender ";
                            }
                            if($bShowRole) {
                                $tmpstr = trim($tmpstr)." $Indv_role ";
                            }
                            $tmpstr = trim($tmpstr);
                            // SHOW ROLE
                            pdf_setfont($pdf, $NormalPDFFont_bold, $tinyFontSize);
                            if(strlen($Indv_SchoolGrade)>0) {
                                if (strlen($tmpstr)>0){
                                    $tmpstr = $tmpstr." in ";
                                }
                                $tmpstr = "(".$tmpstr."$Indv_SchoolGrade)";
                                pdf_show_xy($pdf, $tmpstr, $x+$intIndvRoleIndentX, $y);
                            }else
                            {
                                if(strlen($tmpstr)>0) {
                                    pdf_show_xy($pdf, "(".trim("$tmpstr").")", $x+$intIndvRoleIndentX, $y);
                                }
                            }

                            pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                            $y_tmp = $y;
                            $y_tmp2 = $y;

                            $tmp_pos = 1;
                            $tmp_posTxt[1] = "";
                            $tmp_posTxt[2] = "";
                            $tmp_posTxt[3] = "";
                            $tmp_posTxt[4] = "";

                            if(!is_null($Indv_WorkPhoneNum) and strlen($Indv_WorkPhoneNum)>0) {
                                $y_tmp = $y_tmp - $intSmallLineSepSize;
                                // SHOW WORK PHONE
                                //pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
                                $tmp_posTxt[$tmp_pos] = "W:$Indv_WorkPhoneNum";
                                //pdf_show_xy($pdf, "W:$Indv_WorkPhoneNum", $x+$intFirstDetailsX , $y_tmp);
                                $tmp_pos++;
                            }
                            if(!is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)>0) {
                                $y_tmp = $y_tmp - $intSmallLineSepSize;
                                //								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
                                // SHOW MOBILE PHONE
                                $tmp_posTxt[$tmp_pos] = "M:$Indv_MobilePhoneNum";
                                //								pdf_show_xy($pdf, "M:$Indv_MobilePhoneNum", $x+$intFirstDetailsX , $y_tmp);
                                $tmp_pos++;
                            }
                            if(!is_null($Indv_WorkEmail) and strlen($Indv_WorkEmail)>0) {
                                $y_tmp2 = $y_tmp2 - $intSmallLineSepSize;
                                //								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
                                $tmp_posTxt[$tmp_pos] = "W:$Indv_WorkEmail";
                                $tmp_pos++;


                                // SHOW WORK EMAIL
                                if(is_null($Indv_WorkPhoneNum) || strlen($Indv_WorkPhoneNum)==0 || is_null($Indv_MobilePhoneNum) and strlen($Indv_MobilePhoneNum)==0) {
                                    //									pdf_show_xy($pdf, "W:$Indv_WorkEmail" , $x+$intFirstDetailsX  , $y_tmp2);

                                } else {
                                    //								pdf_show_xy($pdf, "W:$Indv_WorkEmail" , $x+$intLeftEmailDetailsIndentX , $y_tmp2);
                                }
                            }
                            if(!is_null($Indv_HomeEmail) and strlen($Indv_HomeEmail)>0) {
                                $y_tmp2 = $y_tmp2 - $intSmallLineSepSize;
                                //								pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
                                // SHOW HOME EMAIL
                                $tmp_posTxt[$tmp_pos] = "H:$Indv_HomeEmail";
                                //								pdf_show_xy($pdf, "H:$Indv_HomeEmail" , $x+$intLeftEmailDetailsIndentX , $y_tmp2);
                            }

                            //							pdf_setfont($pdf, $NormalPDFFont, $tinyFontSize);
                            $tmp_pos = 1;
                            while (strlen($tmp_posTxt[$tmp_pos])>0){

                                if ($tmp_pos==1){

                                    $tmpx=$x+$intFirstDetailsX;
                                    $tmpy=$y-$intSmallLineSepSize;
                                }
                                if ($tmp_pos==2){
                                    $tmpx=$x+$intLeftEmailDetailsIndentX+50;
                                    $tmpy=$y-$intSmallLineSepSize;
                                }
                                if ($tmp_pos==3){
                                    $tmpx=$x+$intFirstDetailsX;
                                    $tmpy=$y-$intSmallLineSepSize-$intSmallLineSepSize;
                                }
                                if ($tmp_pos==4){
                                    $tmpy=$y-$intSmallLineSepSize-$intSmallLineSepSize;
                                    $tmpx=$x+$intLeftEmailDetailsIndentX+50;
                                }


                                pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                                if (strlen($tmp_posTxt[$tmp_pos])>25){
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-0.5);
                                }
                                if (strlen($tmp_posTxt[$tmp_pos])>29){
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-1);
                                }
                                if (strlen($tmp_posTxt[$tmp_pos])>32){
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-1.5);
                                }
                                if (strlen($tmp_posTxt[$tmp_pos])>35){
                                    pdf_setfont($pdf, $NormalPDFFont, $smallFontSize-2);
                                }

                                pdf_show_xy($pdf, $tmp_posTxt[$tmp_pos] , $tmpx , $tmpy);

                                $tmp_pos++;
                            }

                            $y = $y_tmp2;
                            if($y > $y_tmp) {
                                $y = $y_tmp;
                            }
                            pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
                            //			pdf_show_xy($pdf, "..", $x-10, $y);
                            // insert a seperator row
                            $y = $y - $intLineSepSize;
                        }
                    } // end Children/Others Individual Loop

                    // Check for end of page


                    $y = $y - $intLineSepSize;

                    if($y > $bottom_image_Y ) {
                        //pdf_show_xy($pdf, $bottom_image_Y."bi" , 10 , $y+80);
                        $y = $bottom_image_Y - $intMinSepAfterAddrY;
                        $bottom_image_Y = $y;
                    } else {
                        if ( $y > ($intTopOfAddressY ) )
                        {
                            $y = $intTopOfAddressY;//- $intMinSepAfterAddrY;
                        } else {
                            $y = $y + 20;
                        }

                    }
                    //pdf_show_xy($pdf, $intTopOfAddressY."ta" , 10 , $y+50);

                    //pdf_show_xy($pdf, $y."a" , 10 , $y);
                    //pdf_show_xy($pdf, $y."b" , 10 , $y);
                    //
                    // Insert line at end of Family
                    //
                    if (!$bDebug){
                        if($intPageSize==1){
                            PDF_moveto($pdf,$intPage1LeftX  ,$y );
                            PDF_lineto($pdf,$intPage1RightX, $y );
                            PDF_stroke($pdf);
                            $y = $y - $intLineSepSize;
                        } else {
                            PDF_moveto($pdf,$intPage2LeftX  ,$y );
                            PDF_lineto($pdf,$intPage2RightX, $y );
                            PDF_stroke($pdf);
                            $y = $y - $intLineSepSize;

                        }
                    }
                    $diff=$prevy-$y;
                    $PACTS_cfg->LogData2("y = $y, diff=,".$diff.", Fmly_Indvcnt = ,$Fmly_Indvcnt, at end of Family =".$row_Fmly["FamilyShortName"]);
                    $prevy = $y;

                } // end if count family
            } // end while family
            $pageFamily = "";
            if 	($strLR == "R"){
                //				pdf_end_page($pdf);
            }
        } //end if
        $ActualIntPageCount++;
        if ($bDebug) echo " == pageOrder[$ActualIntPageCount] = ".@$pageOrder[$ActualIntPageCount]."<p>\n";
        /////////////////////////////////////////////////////////////////////////////////////
    } //end while
} // end if rowcount


// Middle footer
//	pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
//	pdf_show_xy($pdf, "Page $intPageCount", $intPageSizeX/2-10, $intPageCountPosY);


$PACTS_cfg->endpageload = $PACTS_cfg->utime();

$run_time = $PACTS_cfg->endpageload - $PACTS_cfg->startpageload;


if ($resultsnumber_Fmly == 0 || $bDebug)  {
    //Show page generation times
    print "Page generated in " . substr($run_time, 0, 5) . " secs<br />";
} ELSE {
    //	pdf_setfont($pdf, $NormalPDFFont, $smallFontSize);
    //	pdf_show_xy($pdf, "Page generated in " . substr($run_time, 0, 5) . " secs" , $intPageXMidX, $intPageCountPosY-10);

}


if (!$bDebug and $bPage_Open)	{
    pdf_end_page($pdf);
    pdf_close($pdf);
}

//exit;
if (!$bDebug){
    $buf = @pdf_get_buffer($pdf);
    $len = @strlen($buf);

    header("Content-type: application/pdf");
    header("Content-Length: $len");
    header("Content-Disposition: inline; filename=ChurchDirectory_A5_Landscape__booklet_".date('Ymd_Gis').".pdf");
    print $buf;
}
pdf_delete($pdf);
exit;
?>